<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 警告条的显示 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条的显示 -->
      <el-steps
        :space="200"
        :active="activeIndex * 1"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-tabs
        :tab-position="'left'"
        v-model="activeIndex"
        :before-leave="beforeLeave"
        @tab-click="tabClicked"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form
            :model="goodsInfoForm"
            :rules="goodsInfoRules"
            ref="goodsInfoRef"
            label-width="100px"
            label-position="top"
          >
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsInfoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="goodsInfoForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsInfoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsInfoForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsInfoForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form label-position="top">
            <el-form-item
              v-for="item in manyCateList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="name"
                  v-for="(name, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form>
            <el-form-item
              v-for="item in onlyCateList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <!-- action表示图片要上传到的后台API地址 -->
          <el-upload
            :action="uploadURL"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :headers="headerObj"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="goodsInfoForm.goods_introduce"></quill-editor>
          <el-button type="primary" @click="addBtn">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片" :visible.sync="previewImgVisible" width="50%">
      <img :src="imgUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data() {
    return {
      activeIndex: '0',
      goodsInfoForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      goodsInfoRules: {
        goods_name: {
          required: true,
          message: '请输入商品名称',
          trigger: 'blur'
        },
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: {
          required: true,
          message: '请输入商品重量',
          trigger: 'blur'
        },
        goods_number: {
          required: true,
          message: '请输入商品数量',
          trigger: 'blur'
        },
        goods_cat: {
          required: true,
          message: '请选择商品分类',
          trigger: 'blur'
        }
      },
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyCateList: [],
      onlyCateList: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      imgUrl: '',
      previewImgVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类失败！')
      console.log(res.data)
      this.cateList = res.data
    },
    // 级联选择器改变时触发的事件
    handleChange() {
      console.log(this.goodsInfoForm.goods_cat)
      if (this.goodsInfoForm.goods_cat.length !== 3) {
        this.goodsInfoForm.goods_cat = []
      }
    },
    // 在tab标签页跳转前触发的事件
    beforeLeave(activeName, oldActiveName) {
      // console.log('即将离开的标签页' + oldActiveName)
      // console.log('即将跳转的标签页' + activeName)

      if (oldActiveName == '0' && this.goodsInfoForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // tab标签页点击事件
    async tabClicked() {
      if (this.activeIndex === '1') {
        // console.log(this.activeIndex)
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取动态参数失败！')
        console.log(res.data)
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals === ' ' ? [] : item.attr_vals.split(' ')
        })
        this.manyCateList = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取动态参数失败！')
        console.log(res.data)
        this.onlyCateList = res.data
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      console.log(file)
      this.imgUrl = file.response.data.url
      this.previewImgVisible = true
    },
    // 处理移除图片的操作
    handleRemove(file) {
      console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.goodsInfoForm.pics.findIndex(x => x.pic === filePath)
      this.goodsInfoForm.pics.splice(i, 1)
      console.log(this.goodsInfoForm)
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.goodsInfoForm.pics.push(picInfo)
      console.log(this.goodsInfoForm)
    },
    // 商品内容的添加按钮事件
    addBtn() {
      // console.log(this.goodsInfoForm)
      // 表单预校验
      this.$refs.goodsInfoRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')

        // 执行添加的业务逻辑
        const form = _.cloneDeep(this.goodsInfoForm)
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.manyCateList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.goodsInfoForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyCateList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.goodsInfoForm.attrs.push(newInfo)
        })
        //更新form的数据
        form.attrs = this.goodsInfoForm.attrs

        console.log(form)
        // 调用添加商品的接口
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201)
          return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.goodsInfoForm.goods_cat.length === 3) {
        return this.goodsInfoForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-tabs {
  margin-top: 10px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-dialog img {
  width: 100%;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>
